//
// Created by guoshunw on 2021/3/12.
//

#include "Utils.h"
#include <sstream>
#include <iostream>
#include <iomanip>

string common::Utils::hexDump(const unsigned char *buf, size_t len, size_t line_limit) {
    stringstream os;
    stringstream lineAscii;
    using namespace std;


    for (size_t i = 0; i < len; ++i) {
        if (0 == (i % line_limit)) {
            if (!lineAscii.str().empty()) {
                os << " | " << lineAscii.str();
            }
            lineAscii.str(string());
            lineAscii.clear();
            os << endl;
            os << setw(8) << setfill('0') << dec << i;
            os << "  ";
        }
        auto hexNum = (static_cast<uint16_t>(buf[i]) & 0xff);
        os << setw(2) << setfill('0') << hex << hexNum << " ";

        if (isprint(hexNum)) {
            lineAscii << static_cast<unsigned char>(hexNum);
        } else {
            lineAscii << '.';
        }
    }

    if (!lineAscii.str().empty()) {
        stringstream holder;
        auto placeHolderSize = 3 * (line_limit - lineAscii.str().length());
        for (size_t i = 0; i < placeHolderSize; ++i) {
            holder << ' ';
        }
        os << holder.str() << " | " << lineAscii.str();
    }
    os << endl;
    return os.str();
}
